
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.AI;
using UnityEngine.UIElements;

public class MapHandleWindow : EditorWindow
{
    public static MapHandleWindow m_mainWindow;

    [MenuItem("MyWindows/HandlesWindow")]
    public static void OpenWindow() //打开窗口
    {
        m_mainWindow = EditorWindow.GetWindow<MapHandleWindow>();
        m_mainWindow.Show();
    }

    private void OnEnable()
    {
        SceneView.duringSceneGui += OnSceneGUI; //对SceneView的刷新事件进行注册
    }

    private void OnDisable()
    {
        SceneView.duringSceneGui -= OnSceneGUI; //对SceneView的刷新事件取消注册
        MapDrawer.GetInstance().Clear();
    }

    private void OnSceneGUI(SceneView sceneView) //自定义刷新事件的委托方法
    {
        MapDrawer.GetInstance().DrawAll();
    }

    private void CreateGUI()
    {
        EditorWindow view = EditorWindow.GetWindow<SceneView>();

        // Each editor window contains a root VisualElement object
        VisualElement root = rootVisualElement;
        // Import UXML
        var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Editor/New/map_handle.uxml");
        VisualElement xml = visualTree.Instantiate();
        root.Add(xml);

        // 网格生成
        var mapFoldout = root.Q<Foldout>("map");
        var step1Btn = root.Q<Button>("step1");
        var selectInput = root.Q<TextField>("selectIdx");
        step1Btn.RegisterCallback<MouseUpEvent>((evt) =>
        {
            Step1();
            Step2(selectInput.text);
            view.Repaint();
        });

        selectInput.RegisterCallback<ChangeEvent<string>>(evt =>
        {
            Step2(evt.newValue);
            view.Repaint();
        });

        var step3Btn = root.Q<Button>("step3");
        step3Btn.RegisterCallback<MouseUpEvent>((evt) =>
        {
            Step3();
            view.Repaint();
        });

        //一键生成地图
        var onekeyFoldout = root.Q<Foldout>("onekey");
        var onekeyBtn = root.Q<Button>("oneKey");
        onekeyBtn.RegisterCallback<MouseUpEvent>((evt) =>
        {
            Step1();
            Step2(selectInput.text);
            Step3();
            view.Repaint();
        });

        mapFoldout.RegisterCallback<ChangeEvent<bool>>(evt =>
        {
            MapDrawer.GetInstance().IsDrawMap = evt.newValue || onekeyFoldout.value;
            view.Repaint();
        });
        onekeyFoldout.RegisterCallback<ChangeEvent<bool>>(evt =>
        {
            MapDrawer.GetInstance().IsDrawMap = evt.newValue || mapFoldout.value;
            view.Repaint();
        });
        MapDrawer.GetInstance().IsDrawMap = mapFoldout.value || onekeyFoldout.value;

        //生成二维网格
        var arrMapFoldout = root.Q<Foldout>("arrmap");
        arrMapFoldout.RegisterCallback<ChangeEvent<bool>>(evt =>
        {
            MapDrawer.GetInstance().IsDrawArrMap = evt.newValue;
            view.Repaint();
        });
        MapDrawer.GetInstance().IsDrawArrMap = arrMapFoldout.value;
        var gridsizeInput = root.Q<TextField>("gridsize");
        gridsizeInput.RegisterCallback<ChangeEvent<string>>(evt =>
        {
            MapDrawer.GetInstance().SetGridSize(evt.newValue);
            view.Repaint();
        });
        MapDrawer.GetInstance().SetGridSize(gridsizeInput.value);

        var arrBtn = root.Q<Button>("arrbtn");
        arrBtn.RegisterCallback<MouseUpEvent>((evt) =>
        {
            GenArrMap();
            view.Repaint();
        });
        var gridCenterToggle = root.Q<Toggle>("gridCenter");
        gridCenterToggle.RegisterCallback<ChangeEvent<bool>>((evt) =>
        {
            ChangeGridCenter(evt.newValue);
            view.Repaint();
            evt.StopImmediatePropagation();
        },TrickleDown.TrickleDown);

        //寻路
        var pathFoldout = root.Q<Foldout>("pathCount");
        pathFoldout.RegisterCallback<ChangeEvent<bool>>(evt =>
        {
            MapDrawer.GetInstance().IsDrawPath = evt.newValue;
            view.Repaint();
        });
        MapDrawer.GetInstance().IsDrawPath = pathFoldout.value;
        var startPosInput = root.Q<TextField>("startPos");
        var endPosInput = root.Q<TextField>("endPos");
        startPosInput.RegisterCallback<ChangeEvent<string>>(evt =>
        {
            MapDrawer.GetInstance().SetStartPos(evt.newValue);
            view.Repaint();
        });
        endPosInput.RegisterCallback<ChangeEvent<string>>(evt =>
        {
            MapDrawer.GetInstance().SetEndPos(evt.newValue);
            view.Repaint();
        });
        MapDrawer.GetInstance().SetStartPos(startPosInput.text);
        MapDrawer.GetInstance().SetEndPos(endPosInput.text);

        var pathBtn = root.Q<Button>("path");
        pathBtn.RegisterCallback<MouseUpEvent>((evt) =>
        {
            MapPath.CountPath();
            view.Repaint();
        });

        var preViewBtn = root.Q<Button>("preView");
        preViewBtn.RegisterCallback<MouseUpEvent>((evt) =>
        {
            MapDrawer.GetInstance().PreView();
            view.Repaint();
        });
        var nextViewBtn = root.Q<Button>("nextView");
        nextViewBtn.RegisterCallback<MouseUpEvent>((evt) =>
        {
            MapDrawer.GetInstance().NextView();
            view.Repaint();
        });
    }

    private void Step1()
    {
        NavMeshTriangulation nmt = UnityEngine.AI.NavMesh.CalculateTriangulation();
        //1.添加所有寻路三角形
        int id = 1;
        for (int i = 0; i < nmt.indices.Length; i += 3)
        {
            TriangleData t = new TriangleData();
            t.Id = id;
            t.A = nmt.vertices[nmt.indices[i]];
            t.B = nmt.vertices[nmt.indices[i + 1]];
            t.C = nmt.vertices[nmt.indices[i + 2]];
            MapDrawer.GetInstance().AddMapTriangle(t);

            id++;
        }

        Debug.Log("添加所有寻路三角形");
    }

    private void Step2(string str)
    {
        //2.选定三角形索引
        int idx;
        if (!Int32.TryParse(str, out idx)) return;
        MapDrawer.GetInstance().SetSelectTriangle(idx);
        Debug.Log("选定三角形索引");
    }

    private void Step3()
    {
        //3.剔除选取三角形未连接部分
        MapDrawer.GetInstance().CalNeighbourMap();
        Debug.Log("剔除选取三角形未连接部分");
    }

    private void GenArrMap()
    {
        Terrain[] terrains = Terrain.activeTerrains;
        if (terrains.Length <= 0)
        {
            return;
        }

        MapDrawer.GetInstance().TerrainSize = terrains[0].terrainData.size;
        float r = 1f;
        int columnCnt = Mathf.CeilToInt(MapDrawer.GetInstance().TerrainSize.x / r);
        int rowCnt = Mathf.CeilToInt(MapDrawer.GetInstance().TerrainSize.z / r);

        List<GridData> gridMap = new List<GridData>();
        for (int i = 0; i < rowCnt; i++)
        {
            for (int j = 0; j < columnCnt; j++)
            {
                var gridData = new GridData();
                gridData.Id = (i + 1) + "_" + (j + 1);
                gridData.Width = r;
                gridData.Height = r;
                gridData.X = j * r + r / 2;
                gridData.Y = i * r + r / 2;
                gridData.State = GridState.UnWalkable;
                gridData.IsAnchorCenter = false;

                gridMap.Add(gridData);
            }
        }

        //判断是否在三角形内
        foreach (var gridData in gridMap)
        {
            for (int i = 0; i < MapDrawer.GetInstance().Map.Count; i++)
            {
                var t = MapDrawer.GetInstance().Map[i];
                if (t.IsPointInTriangle(new Vector3(gridData.X, 0, gridData.Y)))
                {
                    gridData.State = GridState.Walkable;
                    break;
                }
            }
        }

        MapDrawer.GetInstance().SetArrGridMap(gridMap);
        Debug.Log("生成网格:" + gridMap.Count);
    }

    private void ChangeGridCenter(bool isCenter)
    {
        if (MapDrawer.GetInstance().GridDatas.Count <= 0)
        {
            return;
        }

        if (MapDrawer.GetInstance().GridDatas[0].IsAnchorCenter == isCenter)
        {
            return;
        }
        
        var tSize = MapDrawer.GetInstance().TerrainSize;
        for (int i = 0; i < MapDrawer.GetInstance().GridDatas.Count; i++)
        {
            var gridData = MapDrawer.GetInstance().GridDatas[i];
            gridData.IsAnchorCenter = isCenter;
            if (isCenter)
            {
                gridData.X -= tSize.x / 2;
                gridData.Y -= tSize.z / 2;
            }
            else
            {
                gridData.X += tSize.x / 2;
                gridData.Y += tSize.z / 2;
            }
        }
    }
}